package server

import (
	"crypto/md5"
	"errors"
	"fmt"
	"github.com/doujunyu/gogo/gogo_log"
	"github.com/doujunyu/gogo/sql_aid"
	"go_self/model"
	"go_self/util"
	"math/rand"
	"time"
)

// UserLogin 用户登录
func UserLogin(userId int64) (map[string]interface{}, error) {
	list := make(map[string]interface{})
	list["user_id"] = userId
	//获取用户习惯
	userPropertySql, args := sql_aid.PgTable(model.TableByUserSign).Field("is_admin").Where("user_id = ?", userId).ToSql()
	userProperty, err := sql_aid.DataToMap(model.PgSql.Query(userPropertySql, args...))
	if err != nil || len(userProperty) == 0 {
		gogo_log.Error("server_UserLogin", "用户登录", err.Error())
		return nil, errors.New("用户不存在1")
	}
	//检查店铺
	//shopPropertySql, args := sql_aid.PgTable(model.TableByShop).Where("user_id = ?", userId).Where("status = ?", model.ShopByStatusNormal).ToSql()
	//shopProperty, err := sql_aid.DataToMap(model.PgSql.Query(shopPropertySql, args...))
	//if err != nil || len(shopProperty) == 0 {
	//	userProperty[0]["shop_id"] = int64(0)
	//} else {
	//	userProperty[0]["shop_id"] = shopProperty[0]["id"]
	//}
	list["property"] = userProperty[0]
	//生成token信息
	tokenToStringOne := fmt.Sprintf("%v", userId) + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5One := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringOne)))
	tokenToStringTwo := tokenToMd5One + time.Now().Format("2006-05-04 15:02:01")
	tokenToMd5Two := fmt.Sprintf("%x", md5.Sum([]byte(tokenToStringTwo)))
	token := fmt.Sprintf("%v-%v", userId, tokenToMd5Two)
	//
	tokenStruct := UserToken{ //token保存信息
		Token:   token,
		UserId:  userId,
		IsAdmin: int(userProperty[0]["is_admin"].(int64)),
		//ShopId:  userProperty[0]["shop_id"].(int64),
	}
	if err := tokenStruct.AddToken(); err != nil {
		return nil, err
	}
	list["token"] = token

	return list, nil
}

// UserRegisterByUsername 用户注册
func UserRegisterByUsername(username string, password string) (int64, error) {
	set, args := sql_aid.PgTable(model.TableByUser).Where("username = ?", username).ToSql()
	datas, err := sql_aid.DataToMap(model.PgSql.Query(set, args...))
	if err != nil || len(datas) != 0 {
		return 0, errors.New("账号已经存在")
	}

	userReg := make(map[string]interface{})
	rand.Seed(time.Now().Unix())
	userReg["nick"] = fmt.Sprintf("%d", rand.Intn(100)) + fmt.Sprintf("%d", time.Now().Unix())
	userReg["username"] = username
	userReg["password"] = string(util.Hash(password))
	userReg["time_c"] = time.Now().Format(time.RFC3339)
	tx, err := model.PgSql.Begin()
	defer tx.Rollback()
	userSql, args := sql_aid.PgTable(model.TableByUser).InsertByMap(&userReg)
	var userId int64
	err = tx.QueryRow(userSql+" RETURNING id", args...).Scan(&userId)
	if err != nil {
		return 0, errors.New("添加用户失败")
	}

	userSignReg := make(map[string]interface{})
	userSignReg["user_id"] = userId
	userSignSql, args := sql_aid.PgTable(model.TableByUserSign).InsertByMap(&userSignReg)
	_, err = tx.Exec(userSignSql, args...)
	if err != nil {
		fmt.Println(1, err)
		return 0, errors.New("添加用户标识失败")
	}
	userPropertyReg := make(map[string]interface{})
	userPropertyReg["user_id"] = userId
	userPropertySql, args := sql_aid.PgTable(model.TableByUserProperty).InsertByMap(&userPropertyReg)
	_, err = tx.Exec(userPropertySql, args...)
	if err != nil {
		return 0, errors.New("添加用户钱包失败")
	}
	tx.Commit()
	return userId, nil
}

// UserByList 用户列表
func UserByList(input map[string]string)[]map[string]interface{}{
	if input["orderBy"] == "" { //默认排序
		input["orderBy"] = "id desc"
	}
	//排序
	goodsSql, arge := sql_aid.PgTable(model.TableByUser).Field("id","username","mobile","nick","avatar","status","last_login_ip","last_login_time","time_c").WhereRaw(func(query *sql_aid.PgQuery, i ...interface{}) {
		if i[0].(map[string]string)["nick"] != "" { //用户昵称
			query.Where("nick like ?", "%"+i[0].(map[string]string)["nick"]+"%")
		}
		if i[0].(map[string]string)["username"] != "" { //登录账号
			query.Where("username like %?%", i[0].(map[string]string)["username"])
		}
		if i[0].(map[string]string)["mobile"] != "" { //手机号
			query.Where("mobile like %?%", i[0].(map[string]string)["mobile"])
		}
		if i[0].(map[string]string)["status"] != "" { //状态:1=正常,2=禁用
			query.Where("status = ?", i[0].(map[string]string)["status"])
		}
	}, input).OrderBy(input["orderBy"]).PageSize(input["page"], input["page_size"]).ToSql()
	goodsData, err := sql_aid.DataToMap(model.PgSql.Query(goodsSql, arge...))
	if err != nil {
		gogo_log.Error("server_UserByList", "用户列表", err.Error())
		return []map[string]interface{}{}
	}
	return goodsData
}



